package com.pearlsoft.webapp.sysmgr.userRole;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;

import com.pearlsoft.commons.utils.UUIDUtil;
import com.pearlsoft.webapp.core.annotation.DataSetHandlerComponent;
import com.pearlsoft.webapp.core.dataset.DataSet;
import com.pearlsoft.webapp.core.dataset.Result;
import com.pearlsoft.webapp.core.dataset.spi.ContextDataSetHandler;
import com.pearlsoft.webapp.core.web.util.RightUtil;


/**
 * 
 * @author YEHH
 *
 */
@DataSetHandlerComponent(name = "SysUserRoleDataSetHandler")
public class SysUserRoleDataSetHandler extends ContextDataSetHandler {

	public void handler(DataSet ds, Result result) throws Exception {
		// TODO Auto-generated method stub

	}
	
	public void save(final DataSet ds, Result result) throws Exception {
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		final String userId = (String) ds.getConditions().get("USER_ID");
		String rsql = "delete from SYS_USER_ROLE where USER_ID=?";
		jdbcTemplate.update(rsql, new PreparedStatementSetter() {
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1,userId );
			}
		});
		String iSql = "INSERT INTO SYS_USER_ROLE( USER_ROLE_ID,USER_ID,ROLE_ID) VALUES(?,?,?)";
		while(ds.next()){
			jdbcTemplate.update(iSql, new PreparedStatementSetter() {
				public void setValues(PreparedStatement ps) throws SQLException {
					ps.setString(1, UUIDUtil.get());
					ps.setString(2, userId);
					ps.setString(3, (String) ds.getValue("ROLE_ID"));
				}

			});
		}
		this.buildUserMenuXml(userId);
	}
	
	
	public void buildUserMenuXml(String userId){
		JdbcTemplate jdbcTemplate = this.getBean("jdbcTemplate", JdbcTemplate.class);
		String userSql = "SELECT * FROM SYS_USER WHERE USER_ID=?";
		Map<String, Object> userMap = jdbcTemplate.queryForMap(userSql,userId);
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("MENUS");
		String userCode = userMap.get("USER_CODE").toString();
		root.addAttribute("owner", userCode);
		String sql = "SELECT * FROM (SELECT DISTINCT(C.MENU_ID) FROM (SELECT * FROM sys_user_role   WHERE USER_ID=?) B LEFT JOIN sys_role_menu C " +
				"ON B.ROLE_ID = C.ROLE_ID WHERE C.MENU_ID IS NOT NULL  ) D LEFT JOIN sys_menu F ON D.MENU_ID = F.MENU_ID WHERE F.C_STATUS='1' ORDER BY F.MENU_PARENT_ID,F.MENU_ORDER";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,new Object[] {userId});
		RightUtil.buildUserRightXml(list,userCode);
	}
	


	
}
